package com.bc.web.controller.admin;

import com.bc.web.model.Merch;
import com.bc.web.model.MerchRole;
import com.bc.web.model.MerchUser;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSDate;
import com.fs.common.util.FSMD5;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

public class MerchUserController extends FSController{
	
	public void search(){
		Page<MerchUser> items = MerchUser.dao.search(super.getSearchCondition());
		setPageResultToRequest("items", items);
		render("merch/merchUserList.html");
	}
	
	public void addPage(){
		setAttr("roleList", MerchRole.dao.selectAll());
		render("merch/merchUserAdd.html");
	}
	
	public void updatePage(){
		MerchUser merchUser = MerchUser.dao.findById(getPara("id"));
		setAttr("merch", Merch.dao.selectByMerchCode(merchUser.getMerchCode()));
		setAttr("roleList", MerchRole.dao.selectAll());
		setAttr("item", merchUser);
		render("merch/merchUserUpdate.html");
	}
	
	@Before(Tx.class)
	public void add(){
		MerchUser merchUser = getModel(MerchUser.class,"item",true);
		if(MerchUser.dao.selectByUserName(merchUser.getUserName()) != null){
			renderFail("用户名重复");
		}else{
			Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
			merchUser.setOrgCode(merch.getOrgCode());
			merchUser.setUpdateTime(FSDate.getDateTime());
			merchUser.setPassword(FSMD5.codeFor(merchUser.getPassword()));
			merchUser.setEnable(true);
			merchUser.save();
			renderSuccess();
		}
	}
	
	public void update(){
		MerchUser merchUser = getModel(MerchUser.class,"item",true);
		String newPassword = getPara("newPassword");
		if(StrKit.notBlank(newPassword)){
			merchUser.setPassword(FSMD5.codeFor(newPassword));
		}
		merchUser.setUpdateTime(FSDate.getDateTime());
		merchUser.update();
		renderSuccess();
	}
	
	@Before(Tx.class)
	public void delete(){
		Integer id = getParaToInt("id");
		MerchUser.dao.deleteById(id);
		renderSuccess(false);
	}
	
	@Before(Tx.class)
	public void changeEnable(){
		MerchUser.dao.changeEnable(getParaToInt("id"));
		renderSuccess(false);
	}
}
